package com.ninjas.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 时间工具类
 */
public class DateUtils {
    public static final String YYYY_MM_DD_HH = "yyyy-MM-dd HH:00:00";
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate 最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 查询前一天的日期
     */
    public static String getYesterday() {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        return yesterday.toString();
    }

    public static LocalDateTime parseLocalDateTime(String time) {
        try {
            return LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } catch (DateTimeParseException e) {
            LocalDate localDate = LocalDate.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            return LocalDateTime.of(localDate, LocalTime.MIDNIGHT);
        }
    }

    public static LocalDate parseLocalDate(String time) {
        return LocalDate.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String parse(LocalDateTime time) {
        return time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    public static String parse(LocalDate time) {
        return time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String parseYMD(LocalDateTime time) {
        return time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String parseYM(LocalDateTime time) {
        return time.format(DateTimeFormatter.ofPattern("yyyy-MM"));
    }

    public static LocalDateTime getTodayStart() {
        return LocalDateTime.of(LocalDate.now(), LocalTime.of(0, 0, 0));
    }

    public static LocalDateTime getTodayEnd() {
        return LocalDateTime.of(LocalDate.now(), LocalTime.of(23, 59, 59));
    }

    public static List<LocalDate> splitLocalDate(LocalDate start, LocalDate end) {
        long daysBetween = ChronoUnit.DAYS.between(start, end);
        return IntStream.rangeClosed(0, (int) daysBetween)
                .mapToObj(start::plusDays)
                .collect(Collectors.toList());
    }

    public static List<Integer> splitMonth(LocalDate start, LocalDate end) {
        long monthBetween = ChronoUnit.MONTHS.between(start, end);
        return IntStream.rangeClosed(0, (int) monthBetween)
                .mapToObj(start::plusMonths)
                .map(LocalDate::getMonthValue)
                .collect(Collectors.toList());
    }

    public static List<Integer> splitYear(LocalDate start, LocalDate end) {
        long yearBetween = ChronoUnit.YEARS.between(start, end);
        return IntStream.rangeClosed(0, (int) yearBetween)
                .mapToObj(start::plusYears)
                .map(LocalDate::getYear)
                .collect(Collectors.toList());
    }

    public static LocalDateTime getYearStart(LocalDateTime date) {
        return LocalDateTime.of(LocalDate.of(date.getYear(), 1, 1), LocalTime.MIDNIGHT);
    }

    public static LocalDateTime getYearEnd(LocalDateTime date) {
        return LocalDateTime.of(LocalDate.of(date.getYear(), 12, 31), LocalTime.of(23, 59, 59));
    }

    public static LocalDateTime getMonthStart(LocalDateTime date) {
        return LocalDateTime.of(LocalDate.of(date.getYear(), date.getMonth(), 1), LocalTime.MIDNIGHT);
    }

    public static LocalDateTime getMonthEnd(LocalDateTime date) {
        return LocalDateTime.of(LocalDate.of(
                date.getYear(),
                date.getMonth(),
                date.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth()
        ), LocalTime.of(23, 59, 59));
    }

    public static LocalDateTime getDayStart(LocalDateTime date) {
        return LocalDateTime.of(LocalDate.of(date.getYear(), date.getMonth(), date.getDayOfMonth()), LocalTime.MIDNIGHT);
    }



    public static LocalDateTime getDayEnd(LocalDateTime date) {
        return LocalDateTime.of(LocalDate.of(date.getYear(), date.getMonth(), date.getDayOfMonth()), LocalTime.of(23, 59, 59));
    }
}
